﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace MigrateLinksofWIs
{
    class Logging
    {
        static StreamWriter fLogger;
        static string newfPath = string.Empty;
        static string _runtime = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss").ToString();

        static Logging()
        {
            try
            {

                string currentpath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                newfPath = Path.Combine(Path.Combine(currentpath, "Logs"), "MoveSharedQueryLog_" + _runtime + ".log");
                if (!Directory.Exists(Path.GetDirectoryName(newfPath)))
                {
                    try
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(newfPath));
                    }
                    catch (Exception e)
                    {
                        Mailer.SendMail(e.Message);
                    }

                }

                if (!System.IO.File.Exists(newfPath))
                {
                    fLogger = new StreamWriter(newfPath, true);
                }

            }
            catch (Exception e)
            {
                Mailer.SendMail(e.Message.ToString());
            }
        }
        public static void Log(Exception exception, bool sendMail)
        {
            //    string currentpath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            //    newfPath = Path.Combine(Path.Combine(currentpath, "Logs"), "ScenarioRollUpEngine_" + _runtime + ".log");            
            string details =
               "\r\n Exception Details \r\n" +
                exception.Message + "\r\n" +
                (exception.InnerException != null
                                   ? (exception.InnerException.Message + "\r\n")
                                   : string.Empty) + exception.StackTrace;
            fLogger.WriteLine(details);
            fLogger.Flush();
            if (sendMail)
            {
                Mailer.SendMail(details);
            }
        }
        public static void Log(string message)
        {
            fLogger.WriteLine(message);
            fLogger.Flush();
        }

        [STAThread]
        public static void DeleteOldFiles()
        {
            try
            {
                Int32 days = 30;
                string[] temp = Directory.GetFiles(Path.GetDirectoryName(newfPath));
                DateTime Maxdate = DateTime.Now.AddDays(-1 * days);
                DateTime tempdate;
                TimeSpan ts;
                for (int i = 0; i < temp.Length; i++)
                {
                    tempdate = GetDateFromFileName(Path.GetFileName(temp[i]));
                    ts = DateTime.Now.Subtract(tempdate);
                    if ((ts.Days > days) && (File.Exists(temp[i])))
                    {
                        File.Delete(temp[i]);
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Log(String.Format("DeleteOldFiles \n {0}", e.ToString()));
            }

        }
        /// <summary>
        /// This method is called internally sand it returns the datetime fromthe lof file name.
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private static DateTime GetDateFromFileName(string FileName)
        {
            string[] temp = FileName.Split('_');
            DateTime dt = new DateTime(Convert.ToInt32(temp[1]), Convert.ToInt32(temp[2]), Convert.ToInt32(temp[3]));
            return dt;
        }
    }
    class Mailer
    {
        public static void SendMail(string message)
        {
            try
            {
                SmtpClient client = new SmtpClient("smtphost.redmond.corp.microsoft.com");
                client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                MailMessage mail = new MailMessage();
                //MailAddress tomail=new MailAddress(
                mail.From = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["MailFrom"].ToString());

                foreach (string mailto in System.Configuration.ConfigurationManager.AppSettings["MailTo"].ToString().Split(';'))
                    mail.To.Add(new MailAddress(mailto)); //= System.Configuration.ConfigurationManager.AppSettings["MailTo"].ToString();
                mail.Subject = "Issue in MoveSharedQueries";
                mail.Body = message;
                client.Send(mail);
            }
            catch (Exception e)
            {
                Logging.Log(e, false);
            }
        }
    }
}
